package 线程同步.Lock;

import java.util.concurrent.locks.ReentrantLock;

public class Lock {

    public static void main(String[] args) {
        //线程不安全
        new Thread(new BuyATicket(),"小米").start();
        new Thread(new BuyATicket(),"小虎").start();
        new Thread(new BuyATicket(),"小红").start();

        //lock锁实现线程安全
        new Thread(new BuyATicket_1(), "小米====").start();
        new Thread(new BuyATicket_1(), "小虎====").start();
        new Thread(new BuyATicket_1(), "小红====").start();

    }
}
//不安全的买票方法
class BuyATicket implements Runnable {
    private static int p = 10;

    @Override
    public void run() {
        while (true) {
            if (p > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "买了--->第" + p-- + "票");
            } else {
                break;
            }
        }

    }
}

class BuyATicket_1 implements Runnable {
    private static ReentrantLock lock = new ReentrantLock();//实现lock方法
    private static int p = 10;//票数
    private Boolean test = true;//标记为

    //买票的线程
    @Override
    public void run() {
        while (test){
            mp();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //买票的方法
    public void mp() {
        lock.lock();
        try {
            if (p <= 0) {
                System.out.println("票卖完了");
                test=false;
            }else {
                System.out.println(Thread.currentThread().getName()+"--->买了第"+p--+"张票");
            }
        }finally {
            lock.unlock();
        }
    }
}